import { Navigate } from 'react-router';
import type { FC } from 'react';
import { useEffect, useState } from 'react';
import { tryApiRequest } from '@hdtd/utils';
import { useUserStore } from '@/stores';
import { useUserApi } from '@/apis';

enum EAuthStatus {
  /**
   * 登录验证中
   */
  Checking = 'checking',
  /**
   * 未登录
   */
  NotLogin = 'notLogin',
  /**
   * 已登录
   */
  IsLogin = 'isLogin'
}

type TWithAuthGuard = <GProps extends object = object>(TargetComp: FC<GProps>) => FC<GProps>;

const withAuthGuard: TWithAuthGuard = (TargetComp) => {
  const AuthGuardWrap: typeof TargetComp = (props) => {
    const { accessToken, userInfo, setState, logout } = useUserStore();
    const userApi = useUserApi();
    const [authStatus, setAuthStatus] = useState<EAuthStatus>(EAuthStatus.Checking);

    const authCheck = async () => {
      if (userInfo === null && accessToken === null) {
        setAuthStatus(EAuthStatus.NotLogin);
      } else if (userInfo === null && accessToken !== null) {
        const res = await tryApiRequest(() => userApi.getUserInfo({ accessToken }));
        if (res?.code === API_RESULT_SUCCEED_CODE) {
          setState({ userInfo: res.data });
        } else {
          setAuthStatus(EAuthStatus.NotLogin);
          logout();
        }
      } else if (userInfo !== null) {
        setAuthStatus(EAuthStatus.IsLogin);
      }
    };

    useEffect(() => {
      authCheck();
    }, [userInfo]);

    switch (authStatus) {
      case EAuthStatus.Checking:
        return <div>验证中...</div>;
      case EAuthStatus.NotLogin:
        return <Navigate to="/login" replace />;
      case EAuthStatus.IsLogin:
        return <TargetComp {...props} />;
      default:
        return null;
    }
  };
  return AuthGuardWrap;
};

export default withAuthGuard;
